<template>
	<view v-if="loaded" class="cat2bug-body">
		<page-header :team-id="teamId" :disabled="false" :show-back-button="false">
			<defect-query-tabs ref="defectQueryTabs" @open="handlePickerOpen" @close="handlePickerClose" @input="handleTabChange"></defect-query-tabs>
			<view class="defect-row white">
				<uni-search-bar class="defect-search" :placeholder="`${$t('defect.title')}、${$t('handle-by')}、${$t('module')}`" bgColor="#EEEEEE" cancelButton="none" @input="handleSearch"></uni-search-bar>
			</view>
		</page-header>
		<page-body
			@scrolltolower="handleLowerRefresher"
			@scrolltoupper="handleToupperRefresher"
			@refresherrefresh="handlePullRefresher"
			:refresher-enabled="refresherEnabled"
			:refresher-triggered="refresherTriggered"
		>
			<template v-slot:content>
				<uni-list>
					<uni-swipe-action>
						<uni-swipe-action-item
							v-for="defect in defectList" 
							:key="defect.defectId"
							show="none"
							:auto-close="true"
						>
							<template v-slot:right>
								<veiw class="row">
									<button v-show="assignVisible(defect)" :size="size" @click="handleAssign(defect)" class="button cat2bug-button-assign">{{$t('assign')}}</button>
									<button v-show="repairVisible(defect)" :size="size" @click="handleRepair(defect)" class="button cat2bug-button-repair">{{$t('repair')}}</button>
									<button v-show="rejectVisible(defect)" :size="size" @click="handleReject(defect)" class="button cat2bug-button-reject">{{$t('reject')}}</button>
									<button v-show="passVisible(defect)" :size="size" @click="handlePass(defect)" class="button cat2bug-button-pass">{{$t('pass')}}</button>
									<button v-show="openVisible(defect)" :size="size" @click="handleOpen(defect)" class="button cat2bug-button-open">{{$t('open')}}</button>
									<button v-show="closeVisible(defect)" :size="size" @click="handleClose(defect)" class="button cat2bug-button-close">{{$t('close')}}</button>
									<button v-show="editVisible(defect)" :size="size" @click="handleEdit(defect)" class="button cat2bug-button-modify">{{ $t('modify') }}</button>
									<button v-show="deleteVisible(defect)" :size="size" @click="handleDelete(defect)" class="button cat2bug-button-delete">{{$t('delete')}}</button>
								</veiw>
							</template>
							<uni-list-item @click.native="handleClickDefect($event, defect)" clickable link>
								<template v-slot:body>
									<view class="defect-row">
										<preview-image class="defect-images" :image-urls="defectImageUrls(defect)"></preview-image>
										<view class="defect-col">
											<text>{{defectTitle(defect)}}</text>
											<view class="defect-row defect-row-sub-title">
												<!-- <uni-icons type="left" size="10" class="back-button"></uni-icons> -->
												<view>
													<text>{{ $t('defect.life-time') }}:</text>
													<text class="defect-statistics-value">{{defectLife(defect)}}</text>
												</view>
												<view>
													<text>{{$i18n.t('reject')}}:</text>
													<text class="defect-statistics-value">{{defect.rejectCount}}</text>
												</view>
											</view>
											<view class="defect-row">
												<defect-type-flag :defect="defect"></defect-type-flag>
												<defect-state-flag :defect="defect"></defect-state-flag>
											</view>
										</view>
									</view>
								</template>
							</uni-list-item>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</uni-list>
				<uni-load-more v-if="loaded" :status="loadStatus" @clickLoadMore="handleLowerRefresher" />
			</template>
		</page-body>
		<uni-fab 
			ref="fab"
			v-if="loaded"
			v-show = "fabVisible"
			:content="fabMenu" 
			horizontal="right" 
			vertical="bottom"
			direction="vertical" 
			@trigger="handleFabClick"></uni-fab>
		<!-- 指派对话框 -->
		<assign-popup ref="assignPopup" :safe-area="false" @log="handleDefectLog"></assign-popup>
		<!-- 修复对话框 -->
		<repair-popup ref="repairPopup" :safe-area="false" @log="handleDefectLog"></repair-popup>
		<!-- 驳回对话框 -->
		<reject-popup ref="rejectPopup" :safe-area="false" @log="handleDefectLog"></reject-popup>
		<!-- 通过对话框 -->
		<pass-popup ref="passPopup" :safe-area="false" @log="handleDefectLog"></pass-popup>
		<!-- 开启对话框 -->
		<open-popup ref="openPopup" :safe-area="false" @log="handleDefectLog"></open-popup>
		<!-- 关闭对话框 -->
		<close-popup ref="closePopup" :safe-area="false" @log="handleDefectLog"></close-popup>
		<!-- 修改对话框 -->
		<modify-popup ref="modifyPopup" :safe-area="false" @log="handleDefectLog"></modify-popup>
	</view>
</template>

<script>
	import { listDefect, getDefect, delDefect } from "@/api/system/defect.js"
	import { updateConfig } from '@/api/system/user.js'
	import config from '@/config'
	import {lifeTime} from "@/utils/defect"
	import {checkPermi} from "@/utils/permission";
	import { PROCESSING_STATE, AUDIT_STATE, RESOLVED_STATE, REJECTED_STATE, CLOSE_STATE,
		checkAssignPermi, checkRepairPermi, checkRejectPermi, checkPassPermi, checkClosePermi, checkOpenPermi, checkDeletePermi, checkEditPermi
	} from "@/utils/defect.js"
	import PreviewImage from '@/components/preview-image/index.vue'
	import DefectTypeFlag from '@/components/defect/defect-type-flag/index.vue'
	import DefectStateFlag from '@/components/defect/defect-state-flag/index.vue'
	import DefectQueryTabs from '@/components/defect/defect-query-tabs/index.vue'
	import DefectTools from '@/components/defect/defect-tools/index.vue'
	import AssignPopup from "@/components/defect/defect-tools/assign-popup.vue"
	import RepairPopup from "@/components/defect/defect-tools/repair-popup.vue"
	import RejectPopup from "@/components/defect/defect-tools/reject-popup.vue"
	import PassPopup from "@/components/defect/defect-tools/pass-popup.vue"
	import OpenPopup from "@/components/defect/defect-tools/open-popup.vue"
	import ClosePopup from "@/components/defect/defect-tools/close-popup.vue"
	import ModifyPopup from "@/components/defect/defect-tools/modify-popup.vue"
	
	export default {
		name: 'DefectList',
		components: { PreviewImage, DefectTypeFlag, DefectStateFlag, DefectTools, DefectQueryTabs,
			AssignPopup, RepairPopup, RejectPopup, PassPopup, OpenPopup, ClosePopup, ModifyPopup
		},
		data() {
			return {
				// 页面传过来的参数
				option: {},
				// 列表中缺陷总数量
				total: 0,
				// 项目列表
				defectList: [],
				// 显示的加载状态
				loadStatus: 'more',
				// 当前加载页数
				currentPageNum: 1,
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					orderByColumn: 'projectNum',
					isAsc: 'desc',
					defectType: null,
					defectName: null,
					projectId: null,
					testPlanId: null,
					caseId: null,
					dataSources: null,
					dataSourcesParams: null,
					moduleId: null,
					moduleVersion: null,
					createBy: null,
					updateTime: null,
					createTime: null,
					updateBy: null,
					defectState: null,
					handleBy: null,
					handleTime: null,
					defectLevel: null,
					params:{}
				},
				// 是否可以下拉列表
				refresherEnabled: true,
				// 列表是否在下拉刷新状态
				refresherTriggered: false,
				// 悬浮菜单内容
				fabMenu: [{
						iconPath: '/static/images/system/defect/task.png',
						selectedIconPath: '/static/images/system/defect/task.png',
						text: this.$i18n.t('TASK'),
						active: false
					},{
						iconPath: '/static/images/system/defect/demand.png',
						selectedIconPath: '/static/images/system/defect/demand.png',
						text: this.$i18n.t('DEMAND'),
						active: false
					},{
						iconPath: '/static/images/system/defect/bug.png',
						selectedIconPath: '/static/images/system/defect/bug.png',
						text: this.$i18n.t('BUG'),
						active: false
					},
				],
				// 悬浮菜单是否显示
				fabVisible: true,
			}
		},
		computed: {
			/** 是否加载完成  */
			loaded() {
				return (this.$i18n && this.$i18n.locale)?true:false;
			},
			/** 当前团队ID */
			teamId() {
			    return this.$store.state.user.config.currentTeamId;
			},
			/** 当前项目名称 */
			projectId() {
			    return this.$store.state.user.config.currentProjectId;
			},
			/** 获取当前成员id */
			currentMemberId() {
				return this.$store.state.user.id;
			},
			/** 标记采集的五角星颜色 */
			collectColor: function() {
				return function (project) {
					return project.collect?'#f7ba2a':'#c6d1de'
				}
			},
			defectTitle: function() {
				return function(defect) {
					return `#${defect.projectNum} ${defect.defectName}`
				}
			},
			defectImageUrls: function() {
				return function(defect) {
					return defect && defect.imgUrls?defect.imgUrls.split(',').map(m=>config.baseUrl + m):[];
				}
			},
			/** 缺陷的存活时间 */
			defectLife: function() {
			  return function (defect) {
				return lifeTime(defect);
			  }
			},
			loaded: function() {
				return this.$i18n.locale?true:false;
			},
			// 指派
			assignVisible: function () {
			  return function(defect) {
				  return checkAssignPermi(defect, this.currentMemberId);
			  }
			},
			// 修复
			repairVisible: function () {
			  return function(defect) {
				  return checkRepairPermi(defect, this.currentMemberId);
			  }
			},
			// 驳回
			rejectVisible: function () {
			  return function(defect) {
				  return checkRejectPermi(defect, this.currentMemberId);
			  }
			},
			// 通过
			passVisible: function () {
			  return function(defect) {
				  return checkPassPermi(defect, this.currentMemberId);
			  }
			},
			// 关闭
			closeVisible: function () {
			  return function(defect) {
				  return checkClosePermi(defect);
			  }
			},
			// 开启
			openVisible: function () {
			  return function(defect) {
				  return checkOpenPermi(defect);
			  }
			},
			deleteVisible: function () {
			  return function(defect) {
				  return checkDeletePermi(defect, this.currentMemberId);
			  }
			},
			editVisible: function () {
			  return function(defect) {
				  return checkEditPermi(defect, this.currentMemberId);
			  }
			},
		},
		onLoad(option) {
			this.option = option;
			this.getDefectList(this.queryParams);
			uni.$on('defect-add', ()=>{
				uni.showToast({
					title: this.$i18n.t('create-success'),
				});
				this.reset();
				this.getDefectList(this.queryParams);
			});
			uni.$on('defect-modify', ()=>{
				uni.showToast({
					title: this.$i18n.t('modify-success'),
				});
				this.reset();
				this.getDefectList(this.queryParams);
			});
			uni.$on('defect-tab-change', ()=>{
				this.$refs.defectQueryTabs.reload();
			});
		},
		methods: {
			/** 重置查询条件 */
			reset() {
				this.refresherTriggered = true;
				this.loadStatus = 'more';
				this.defectList = [];
				this.queryParams.pageNum = 1;
			},
			/** 重置查询参数 */
			resetQueryParams() {
				this.queryParams = {
					pageNum: 1,
					pageSize: 10,
					orderByColumn: 'projectNum',
					isAsc: 'desc',
					defectType: null,
					defectName: null,
					projectId: null,
					testPlanId: null,
					caseId: null,
					dataSources: null,
					dataSourcesParams: null,
					moduleId: null,
					moduleVersion: null,
					createBy: null,
					updateTime: null,
					createTime: null,
					updateBy: null,
					defectState: null,
					handleBy: null,
					handleTime: null,
					defectLevel: null,
					params:{}
				}
			},
			/** 处理标签改变 */
			handleTabChange(tab) {
				if(tab && tab.config) {
					tab.config.isAsc = 'desc';
					tab.config.orderByColumn = 'updateTime';
					if(!tab.config.params) {
						tab.config.params = {
						  defectStates: []
						};
					}
					this.queryParams = tab.config;
				} else {
					this.resetQueryParams();
				}
				this.reset();
				this.getDefectList(this.queryParams);
			},
			/** 处理添加任务 */
			handleAddTask() {
				this.$tab.navigateTo('/subpackage/pages/system/defect/add-task');
			},
			/** 处理添加需求 */
			handleAddDemand() {
				this.$tab.navigateTo('/subpackage/pages/system/defect/add-demand');
			},
			/** 处理添加BUG */
			handleAddBug() {
				this.$tab.navigateTo('/subpackage/pages/system/defect/add-bug');
			},
			/** 处理滚动到最底端刷新事件 */
			handleLowerRefresher() {
				if(this.loadStatus === 'more') {
					this.getDefectList(this.queryParams);
				}
				// this.refresherEnabled = false;
			},
			handleToupperRefresher() {
				// this.refresherEnabled = true;
				// console.log('handleToupperRefresher', this.refresherEnabled)
			},
			/** 处理下拉刷新事件 */
			handlePullRefresher() {
				this.reset();
				this.getDefectList(this.queryParams);
				this.$refs.defectQueryTabs.reload();
			},
			/** 处理点击项目事件 */
			handleClickDefect(e, defect) {
				uni.navigateTo({
					url: '/subpackage/pages/system/defect/detail?defectId='+defect.defectId
				});
			},
			/** 处理搜索事件 */
			handleSearch(e) {
				this.reset();
				this.queryParams.params['search'] = e;
				this.getDefectList(this.queryParams);
			},
			/** 获取缺陷列表 */
			getDefectList(params) {
				this.loadStatus = 'loading';
				params = params||{};
				params.projectId = this.projectId;
				listDefect(params).then(response => {
					this.refresherTriggered = false;
					if(response.rows && response.rows.length>0) {
						this.defectList = [...this.defectList, ...response.rows].filter((item, index, self) =>
							index === self.findIndex((t) => t.defectId === item.defectId)
						);
					}
					this.total = response.total;
					if(this.total > this.defectList.length) {
						this.loadStatus = 'more';
						this.queryParams.pageNum += 1;
					} else {
						this.loadStatus = 'no-more';
					}
				});
			},
			/** 处理悬浮按钮 */
			handleFabClick(e) {
				switch(e.index) {
					case 0:
						// 添加任务
						this.handleAddTask();
						break;
					case 1:
						// 添加需求
						this.handleAddDemand();
						break;
					case 2:
						// 添加BUG
						this.handleAddBug();
						break;
				}
			},
			handlePickerOpen() {
				this.fabVisible = false;
			},
			handlePickerClose() {
				this.fabVisible = true;
			},
			/** 处理指派缺陷 */
			handleAssign(defect){
				this.$refs.assignPopup.open(defect);
			},
			/** 处理驳回缺陷 */
			handleReject(defect) {
			  this.$refs.rejectPopup.open(defect);
			},
			/** 处理修复缺陷 */
			handleRepair(defect) {
			  this.$refs.repairPopup.open(defect);
			},
			/** 处理通过缺陷 */
			handlePass(defect) {
			  this.$refs.passPopup.open(defect);
			},
			handleClose(defect){
			  this.$refs.closePopup.open(defect);
			},
			handleOpen(defect){
			  this.$refs.openPopup.open(defect);
			},
			/** 打开编辑窗体 */
			handleEdit(defect) {
			  this.$refs.modifyPopup.open(defect);
			},
			/** 处理删除缺陷 */
			handleDelete(defect) {
				const self = this;
				uni.showModal({
					title: this.$i18n.t('prompted'),
					content: this.$i18n.t('defect.delete-defect'),
					success: function (res) {
						if (res.confirm) {
							delDefect(defect.defectId).then(res=>{
								self.defectList = self.defectList.filter(d=>d.defectId!=defect.defectId);
								uni.showToast({
									title: self.$i18n.t('delete.success')
								})
							})
						}
					}
				});
			},
			/** 处理缺陷日志事件 */
			handleDefectLog(log) {
				// 遍历已有所有缺陷，找到和日志一样的缺陷，进行更新
				for(let i=0;i<this.defectList.length;i++) {
					const defect = this.defectList[i];
					if(defect.defectId === log.defectId) {
						// 刷新缺陷信息
						getDefect(defect.defectId).then(res=>{
							this.defect = res.data;
							this.$set(this.defectList, i, res.data);
						});
						break;
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.defect-images {
		background-image: url("/static/images/system/defect/defect_img_background.png");
		background-repeat: no-repeat;
		background-position: center center;
		background-size: cover; 
	}
	.defect-title {
		position: sticky;
		position: -webkit-sticky;
		top: 0rpx;
	}
	.white {
		background-color: white;
		width: 100%;
	}
	.defect-search {
		width: 100%;
	}
	.defect-row {
		display: inline-flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		gap: 10rpx;
	}
	.defect-col {
		display: inline-flex;
		flex-direction: column;
		justify-content: center;
		align-items: flex-start;
		gap: 15rpx;
	}
	.defect-row-sub-title {
		font-size: 0.7rem;
		color: #909399;
		gap: 20rpx;
	}
</style>